//
//  RestaurantTableViewController.m
//  Gourmet
//
//  Created by WardenAllen on 15/11/9.
//  Copyright © 2015年 王东. All rights reserved.
//

#import "AppDelegate.h"
#import "HomeTableViewController.h"
#import "HomeTableViewCell.h"
#import "MJRefresh.h"
#import "RestaurantDetailTableViewController.h"
#import "QRCodeReaderViewController.h"

#define kCount 6
#define kScrollHeight 120

@interface HomeTableViewController ()<UIScrollViewDelegate, UISearchBarDelegate> {
    UIScrollView *_scrollView;
    //    NSMutableArray *slideImages;
    UIPageControl *_pageControl;
}
@property (weak, nonatomic) IBOutlet UIView *headerView;
@property (assign, nonatomic) int currentPage;
@property (strong) NSMutableArray *logoDataSource;
@property (strong) NSMutableArray *otherDataSource;
@end

@implementation HomeTableViewController

#pragma mark - Life Cycle 

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.logoDataSource = [NSMutableArray array];
    self.otherDataSource = [NSMutableArray array];
    
//    UIView *hiddenView = [[UIView alloc] initWithFrame:CGRectMake(0, -100, kWIDTH, 40*kWIDTH_RATIO)];
//    [hiddenView setBackgroundColor:[UIColor greenColor]];
//    [self.tableView addSubview:hiddenView];
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, 44)];
    UISearchBar *restaurantSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, kWIDTH-50, 44)];
    restaurantSearchBar.searchBarStyle = UISearchBarStyleMinimal;
    restaurantSearchBar.delegate = self;
    [titleView addSubview:restaurantSearchBar];
    
    UIButton *QRCodeScanBtn = [[UIButton alloc] initWithFrame:CGRectMake(kWIDTH-9-32, 10, 24, 24)];
    [QRCodeScanBtn setImage:[UIImage imageNamed:@"扫一扫.png"] forState:UIControlStateNormal];
    [QRCodeScanBtn addTarget:self action:@selector(QRCodeScanBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:QRCodeScanBtn];
    
    self.navigationItem.titleView = titleView;
    
    UIView *footerView = [[UIView alloc] init];
    self.tableView.tableFooterView = footerView;
    
    
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWIDTH, kScrollHeight*kWIDTH_RATIO)];
    for (int i = 0; i< kCount; i++) {
        UIImageView *imageView = [[UIImageView alloc] init];
        
        // 1.设置frame
        imageView.frame = CGRectMake(kWIDTH*i, 0, kWIDTH, kScrollHeight*kWIDTH_RATIO);
        
        // 2.设置图片
        NSString *imgName = [NSString stringWithFormat:@"%d.jpg", i + 1];
        imageView.image = [UIImage imageNamed:imgName];
        
        [_scrollView addSubview:imageView];
    }
    
    // height == 0 代表 禁止垂直方向滚动
    _scrollView.contentSize = CGSizeMake(kCount * kWIDTH, 0);
    _scrollView.showsHorizontalScrollIndicator = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.delegate = self;
    _scrollView.tag = 1; // 与TableView的ScrollView区分开
    
    [self.headerView addSubview:_scrollView];
    
    // 添加PageControl
    UIPageControl *pageControl = [[UIPageControl alloc] init];
    pageControl.center = CGPointMake(kWIDTH * 0.5, kScrollHeight*kWIDTH_RATIO - 20);
    pageControl.bounds = CGRectMake(0, 0, 150, 50);
    pageControl.numberOfPages = kCount; // 一共显示多少个圆点（多少页）
    // 设置非选中页的圆点颜色
    pageControl.pageIndicatorTintColor = [UIColor yellowColor];
    // 设置选中页的圆点颜色
    pageControl.currentPageIndicatorTintColor = [UIColor greenColor];
    
    // 禁止默认的点击功能
    pageControl.enabled = NO;
    
    [self.headerView addSubview:pageControl];
    _pageControl = pageControl;
    
    [NSTimer scheduledTimerWithTimeInterval:4.0 target:self selector:@selector(updateScrollView:) userInfo:nil repeats:YES];
    
//    __unsafe_unretained UITableView *tableView = self.tableView;
//    
//    // 下拉刷新
//    tableView.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            [tableView.mj_header endRefreshing];
//        });
//    }];
//    
//    // 设置自动切换透明度(在导航栏下面自动隐藏)
//    tableView.mj_header.automaticallyChangeAlpha = YES;
//    
//    // 上拉刷新
//    tableView.mj_offsetY = -22.;
//    tableView.mj_footer.frame = CGRectMake(60, kHEIGHT-50, 200, 50);
//    tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            // 结束刷新
//            [tableView.mj_footer endRefreshing];
//        });
//    }];
    
    AVQuery *query = [AVQuery queryWithClassName:@"RestaurantInfo"];
    //[query whereKey:@"restaurantId" equalTo:@1];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 检索成功
            NSLog(@"Successfully retrieved %lu posts.", (unsigned long)objects.count);
            for (int i=0; i<objects.count; i++) {
                AVObject *restaurantInfo = objects[i];
                AVFile *file = [restaurantInfo objectForKey:@"restaurantLogo"];
                [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                    if (!error) {
                        [self.logoDataSource addObject:[UIImage imageWithData:data]];
                        [restaurantInfo removeObjectForKey:@"restaurantLogo"];
                        [self.otherDataSource addObject:restaurantInfo];
                        if (self.logoDataSource.count == objects.count) {
                            [self.tableView reloadData];
                            NSLog(@"%@", self.otherDataSource);
                        }
                    } else {
                        NSLog(@"%@ %@", error, [error userInfo]);
                    }
                }];
            }
        } else {
            // 输出错误信息
            NSLog(@"Error: %@ %@", error, [error userInfo]);
        }
    }];
    
    //挤掉底部空白 Warning!!!
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, -38, 0);

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self updateScrollView:nil];
}

- (void)viewDidLayoutSubviews {
    _headerView.frame = CGRectMake(0, 0, kWIDTH, kScrollHeight*kWIDTH_RATIO);
}

#pragma mark - UISearchBar Delegate

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    
}

#pragma mark - Actions

- (void)updateScrollView:(NSTimer *)timer {
    if (self.currentPage == kCount-1) {
        self.currentPage = 0;
    } else {
        self.currentPage += 1;
    }
    _pageControl.currentPage = self.currentPage;
    [_scrollView setContentOffset:CGPointMake(kWIDTH*_currentPage, 0) animated:YES];
}

- (void)QRCodeScanBtnClicked:(id)sender {
    QRCodeReaderViewController *codeReaderViewController = [QRCodeReaderViewController new];
    codeReaderViewController.hidesBottomBarWhenPushed = YES;
    
    //codeReaderViewController.delegate = self;
    
    UINavigationController *nav = self.tabBarController.viewControllers[0];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self
                                                                  action:@selector(backBtnClicked:)] ;
    
    backButton.tintColor = [UIColor whiteColor] ;
    codeReaderViewController.navigationItem.leftBarButtonItem = backButton;
    [nav pushViewController:codeReaderViewController animated:YES];
    
}

- (void)backBtnClicked:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIScrollView Delegate

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    int page = scrollView.contentOffset.x / scrollView.frame.size.width;
//    NSLog(@"%d", page);
//    // 设置页码
//    _pageControl.currentPage = page;
//}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 1) {
        self.currentPage = scrollView.contentOffset.x / scrollView.frame.size.width;
        NSLog(@"%d", self.currentPage);
        // 设置页码
        _pageControl.currentPage = self.currentPage;
    }
}

#pragma mark - Table view data source

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100*kWIDTH_RATIO;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.logoDataSource.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScrollHeight*(kWIDTH_RATIO-1);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell *restaurantCell = [tableView dequeueReusableCellWithIdentifier:@"RestaurantCell" forIndexPath:indexPath];
    AVObject *otherInfo = self.otherDataSource[indexPath.row];
    restaurantCell.nameLabel.text = [otherInfo objectForKey:@"restaurantName"];
    restaurantCell.logoImageView.image = self.logoDataSource[indexPath.row];
    
    return restaurantCell;
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    RestaurantDetailTableViewController *rdtvc = (RestaurantDetailTableViewController *)[[AppDelegate globalDelegate] RestaurantDetailTableViewController];
    AVObject *otherInfo = [self.otherDataSource objectAtIndex:indexPath.row];
    //先转化为NSString
    NSString *restaurantId = [otherInfo objectForKey:@"restaurantId"];
    NSString *restaurantName = [otherInfo objectForKey:@"restaurantName"];
    float rank = [[otherInfo objectForKey:@"rank"] floatValue];
    NSString *rankCount = [otherInfo objectForKey:@"rankCount"];
    
    rdtvc.restaurantId = [restaurantId integerValue];
    rdtvc.restaurantName = restaurantName;
    rdtvc.rank = rank;
    rdtvc.rankCount = [rankCount integerValue];
    
    [self.navigationController pushViewController:rdtvc animated:YES];
}

@end
